package com.kun.service.service;

import com.kun.common.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.MyException;
import org.csource.fastdfs.StorageClient1;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@Service
public class FastDfsService {

    private final StorageClient1 storageClient1;

    public FastDfsService(StorageClient1 storageClient1) {
        this.storageClient1 = storageClient1;
    }

    /**
     * 文件上传
     */
    public String upload(MultipartFile file) {
        try {
            Assert.isTrue(file.getOriginalFilename() != null, "文件名不能为空");
            // 获取文件扩展名
            String fileSuffix = FileUtils.getFileSuffix(file.getOriginalFilename());
            // 执行上传
            return storageClient1.upload_file1(file.getBytes(), fileSuffix, null);
        } catch (IOException | MyException | ArrayIndexOutOfBoundsException e) {
            log.error("fastdfs上传文件失败：{}", e.getMessage());
            return null;
        }
    }

    /**
     * 文件删除
     *
     * @param groupName 组名 group1
     * @param fileName  文件名 M00/00/00/ezle4Wa4XqeAG652ACb7kEitkFc133.png
     */
    public boolean delete(String groupName, String fileName) {
        try {
            return storageClient1.delete_file(groupName, fileName) == 0;
        } catch (IOException | MyException e) {
            log.error("fastdfs删除文件失败：{}", e.getMessage());
            return false;
        }
    }

}
